package online.westonline.com.westonline.ui;

import android.content.Intent;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;

import com.alamkanak.weekview.WeekViewEvent;
import com.easy.west.westclient.api.workplan.baen.Event;
import com.easy.west.westclient.api.workplan.baen.EventList;
import com.easy.west.westclient.api.workplan.event.GetAllEvent;
import com.grandbroad.online.greendao.EventModelDao;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.entry.EventModel;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.UiUtlis;

/**
 * 工作计划
 */
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class WorkPlanActivity extends WeekViewctivity {
    private boolean flag=true;
    private List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
    private List<EventModel> eventModels = new ArrayList<>();
    private EventModelDao modelDao;
    private Handler myhandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==1)
            {
                parseDataAgain();
            }
            return true;
        }
    });

    /**
     * 为了视图展示的拆分
     */
    private void parseDataAgain() {
        for (EventModel eventModel:eventModels)
        {
            events.add(eventModel.toWeekViewEvent());
        }
        getWeekView().notifyDatasetChanged();

    }

    @Override
    public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
        List<WeekViewEvent> eventList = new ArrayList<>();
        //获取年月
        for (WeekViewEvent event:events)
        {
            if (eventMatches(event,newYear,newMonth))
            {
                eventList.add(event);
            }

        }
        return eventList;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //重启activity
        if (flag)
        {
            flag =false;
        }
        else
        {
            flag =true;
            //重启activity
            Intent intent = getIntent();
            finish();
            startActivity(intent);

        }
    }

    /**
     * Checks if an event falls into a specific year and month.
     * @param event The event to check for.
     * @param year The year.
     * @param month The month.
     * @return True if the event matches the year and month.
     */
    private boolean eventMatches(WeekViewEvent event, int year, int month) {
        return (event.getStartTime().get(Calendar.YEAR) == year && event.getStartTime().get(Calendar.MONTH)+1 == month) || (event.getEndTime().get(Calendar.YEAR) == year && event.getEndTime().get(Calendar.MONTH)+1 == month);
    }

    @Override
    protected void initdata() {
        //请求数据
        MyApplication.getClient().findAllPlan(1);
    }

    /**
     * 处理从网络上拿出来的数据
     * @param eventList
     */
    private void parseData(final EventList eventList) {
        //子线程操作
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (eventList.getData()!=null) {

                    List<Event> events = eventList.getData();
                    for (Event event : events)
                    {
                        //转化为modle
                        EventModel model = new EventModel();
                        String date = event.getDate();
                        model.setMEndTime(event.getEndtime());
                        model.setMStartTime(event.getStarttime());
                        model.setMAllday(event.isTop());
                        model.setDate(event.getDate());
                        model.setYear(Integer.parseInt(date.split("-")[0]));
                        model.setMonth(Integer.parseInt(date.split("-")[1]));
                        model.setDay(Integer.parseInt(date.split("-")[2]));
                        model.setMAllday(event.isTop());
                        model.setMName(event.getContent());
                        model.setId(event.getId());
                        model.setMColor(UiUtlis.RandomColor());
                        eventModels.add(model);
                    }
                    Message message = new Message();
                    message.what=1;
                    myhandler.sendMessage(message);
                    myhandler.obtainMessage();
                }
            }
        }).start();
    }

    @Override
    public void onEventClick(WeekViewEvent event, RectF eventRect) {
        //实现点击跳转
        /*
        Bundle bundle = new Bundle();
        bundle.putSerializable("event",event);
        Intent intent = new Intent(this,PlanInfoActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
        */

    }

    /**
     * 获取计划
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void findallPlan(GetAllEvent event)
    {
        if (event.isOk())
        {
            EventList eventList = event.getBean();
            if (eventList.getStatus()!=1)
            {
                //失败了
                //数据库获取
                eventModels = modelDao.loadAll();
                return;
            }
            //数据拆分
            parseData(eventList);
        }
    }





}
